'use strict';
const AV = require('leanengine');
const async = require('async');


exports.info = function (req, res, next) {

    //商品详情的信息
    let goodsInfo = {};
    let query = new AV.Query('Goods');
    query.equalTo('goods_id', 0);
    query.first().then(function (results) {
        goodsInfo.goods = results[0];
        return new AV.Query('Brand').limit(1).find();

    }).then(function (brand) {
        goodsInfo.brands = brand[0];
        //获取商品相册
        return new AV.Query('Gallery').limit(5).find();
    }).then(function (gallery) {
        goodsInfo.gallery = gallery;
        res.json(goodsInfo);
    }).catch(function (error) {
        console.log(error);
        next(error);
    });

};


//统计商品总数
exports.count = function (req, res, next) {

    //商品详情的信息
    let query = new AV.Query('Goods');
    query.count().then(function (count) {
        returnJson.code = 200;
        returnJson.data = count;

        return res.json(returnJson);
    }).catch(function (error) {
        console.log(error);
        next(error);
    });


};

exports.list = function (req, res, next) {

    let id = req.param('id');
    (async function () {

        let allCategory = await new AV.Query('Category').find();
        let childs = getChilds(allCategory, id);
        let childIds = getCategoryIds(childs);
        childIds.push(id);
        console.log(childIds);

        let goodsList = await new AV.Query('Goods')
            .select(['goodsId', 'name', 'image', 'shopPrice'])
            .equalTo('cat_id', parseInt(id))
            .find();

        returnJson.code = 200;
        returnJson.data = goodsList;
        return res.json(returnJson);
    })();

};

exports.search = function (req, res, next) {

    let keyword = req.body.keyword;
    let ip = req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
    console.log(req.session);
    (async function () {
        let results = await new AV.Query('Goods')
            .select(['goodsId', 'name', 'image', 'shopPrice'])
            .contains('name', keyword)
            .limit(20)
            .find();

        //记录搜索结果
        let SearchHistory = AV.Object.extend('SearchHistory');
        let searchHistory = new SearchHistory();
        searchHistory.set('keyword', keyword);
        searchHistory.set('fromIp', ip);
        searchHistory.set('fromDevice', 'wxapp');
        await searchHistory.save();

        returnJson.code = 200;
        returnJson.data = results;

        return res.json(returnJson);
    })();

};

exports.searchHelp = function (req, res, next) {

    let keyword = req.body.keyword;
    new AV.Query('SearchHistory')
        .select(['keyword'])
        .contains('keyword', keyword)
        .limit(20)
        .equalTo('isDelete', false)
        .find()
        .then(function (results) {
            returnJson.code = 200;
            returnJson.data = results;

            return res.json(returnJson);
        }).catch(function (error) {
        console.log(error);
    });

};

exports.historyKeyword = function (req, res, next) {

    let keyword = req.body.keyword;
    new AV.Query('SearchHistory')
        .select(['keyword'])
        .equalTo('isDelete', false)
        .limit(10)
        .find()
        .then(function (results) {
            returnJson.code = 200;
            returnJson.data = results;

            return res.json(returnJson);
        }).catch(function (error) {
        console.log(error);
    });

};

exports.hotKeyword= function (req, res, next) {

    new AV.Query('SearchHistory')
        .select(['keyword'])
        .equalTo('isDelete', false)
        .equalTo('isHot', true)
        .limit(10)
        .find()
        .then(function (results) {
            returnJson.code = 200;
            returnJson.data = results;

            return res.json(returnJson);
        }).catch(function (error) {
        console.log(error);
    });

};

exports.clearKeywordHistory = function (req, res, next) {

    //let keyword = req.body.keyword;

    (async function () {
        let list = await new AV.Query('SearchHistory')
            //.contains('keyword', keyword)
            .find();
        let objects = [];
        for(let v of list){
            console.log(v.get('id'));
            let item = AV.Object.createWithoutData('SearchHistory', v.get('id'));
            item.set('isDelete', true);
            objects.push(item);
        }
        await AV.Object.saveAll(objects);
        returnJson.code = 200;
        return res.json(returnJson);
    })();

};


/**
 * 递归获取子分类
 * @param allCategory
 * @param catId
 * @returns {Array}
 */
function getChilds(allCategory, catId) {
    var treeArr = [];

    for(let i = 0; i < allCategory.length; i++){
        let itemCat = allCategory[i];
        if (catId == itemCat.get('parent_id')){
            treeArr.push(itemCat);
            treeArr.concat(getChilds(allCategory, itemCat.get('cat_id')));
        }
    }

    return treeArr;
}


function getCategoryIds(category) {
    let ids = [];
    for (let i = 0; i < category.length; i++){
        ids.push(category[i].get('cat_id'));
    }

    return ids;
}